package com.delong.spring.handler.user;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.delong.model.user.User;
import com.delong.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	private UserService service = new UserService();
	public final Integer SESSION_TIMEOUT_IN_SECONDS = 60 * 30;

	@RequestMapping("/login")
	public String loginRender(Map<String, Object> model, ServletRequest req) {
		HttpServletRequest request = (HttpServletRequest) req;
		if (request.getSession(false) != null) {

			return "redirect:/app/list";
		}
		return "user/User";
	}

	@ResponseBody
	@RequestMapping(value = "/auth", method = RequestMethod.POST)
	public String Login(Map<String, Object> model, ServletRequest req, ServletResponse res,
			@RequestParam(value = "username", defaultValue = "") String username,
			@RequestParam(value = "password", defaultValue = "") String password) throws IOException {
		// HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = request.getSession(false);
		JSONObject result = new JSONObject();
		if (session == null) {
			User user = this.service.selectUser(username, password);
			if (user != null) {
				session = request.getSession();
				session.setMaxInactiveInterval(SESSION_TIMEOUT_IN_SECONDS);
				session.setAttribute("username", user.getUsername());
				result.put("code", 0);
				result.put("target", "/app/list");

			} else {
				result.put("code", 1);
				result.put("msg", "用户名或密码错");
			}

		} else {
			result.put("code", 0);
			result.put("target", "/app/list");
		}
		return result.toJSONString();
	}

	@RequestMapping("/loginout")
	public String Login(Map<String, Object> model, ServletRequest req, ServletResponse res) {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = request.getSession();
		session.invalidate();
		return "user/User";
	}

}
